package com.datamanage.auth.service.impl;

import com.datamanage.auth.util.JwtUtil;
import com.datamanage.user.entity.User;
import com.datamanage.user.repository.UserRepository;
import com.datamanage.auth.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class AuthServiceImpl implements AuthService {
    
    @Autowired
    private AuthenticationManager authenticationManager;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Override
    public String authenticate(String username, String password) {
        try {
            // 使用Spring Security进行认证
            authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(username, password)
            );
            
            // 认证成功后生成JWT Token
            User user = userRepository.findByUsernameWithGroupsAndCompany(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
                
            return jwtUtil.generateToken(user);
        } catch (AuthenticationException e) {
            throw new RuntimeException("用户名或密码错误");
        }
    }
    
    @Override
    public User getCurrentUser(String token) {
        String username = jwtUtil.getUsernameFromToken(token);
        return userRepository.findByUsernameWithGroupsAndCompany(username)
            .orElseThrow(() -> new RuntimeException("用户不存在"));
    }
    
    @Override
    public boolean validateToken(String token) {
        try {
            String username = jwtUtil.getUsernameFromToken(token);
            User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
            return jwtUtil.validateToken(token, user);
        } catch (Exception e) {
            return false;
        }
    }
}